package com.youthfilmic.yuejian.controller;

import com.youthfilmic.yuejian.dao.ApplicationDao;
import com.youthfilmic.yuejian.dao.SubjectDao;
import com.youthfilmic.yuejian.dao.UserDao;
import com.youthfilmic.yuejian.domain.Application;
import com.youthfilmic.yuejian.domain.Subject;
import com.youthfilmic.yuejian.domain.User;
import com.youthfilmic.yuejian.service.ApplicationService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * Created by youweixi on 15/10/10.
 */
@Controller
@RequestMapping("/main/application")
public class ApplicationController {
    @Resource
    private UserDao userDao;
    @Resource
    private SubjectDao subjectDao;
    @Resource
    private ApplicationDao applicationDao;
    @Autowired
    private ApplicationService applicationService;


    @ModelAttribute("userId")
    private Long getUserId(HttpSession session){
        Long userId = (Long) session.getAttribute("userId");
        return userId;
    }

    @RequestMapping("/make")
    public String makeApplication(
            @ModelAttribute("userId") Long userId,
            @RequestParam(value="subjectId" , required = false) Long subjectId,
            Model model
    ){
        User user = userDao.findOne(userId);
        Subject subject = subjectDao.findOne(subjectId);
        //设置初始信息
        Application application = new Application();
        application.setSubjectId(subjectId);
        application.setSubjectTitle(subject.getTitle());
        application.setRealName(user.getName());
        application.setPhone(user.getPhone());
        application.setWeixin(user.getWeixin());
        application.setRegion(user.getRegion());
        application.setPresenter(user.getPresenter());
        application.setPrice(subject.getPrice());
        application.setDuration(subject.getDuration());
        model.addAttribute("application" , application);
        return "main/application/application-post";
    }

    @RequestMapping("/make.do")
    public String doApplication(
            Application application,
            @ModelAttribute("userId") Long userId,
            @RequestParam(value="subjectId" , required = false) Long subjectId
    ){
        //创建application
        application = applicationService.makeApplication(userId , subjectId , application);
        return "redirect:/main/pay/pay?applicationId=" + application.getId();
    }



}
